package org.whale.springcloud.eureka.user.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class MyFilter extends ZuulFilter {

  private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);

  @Override
  public String filterType() {

    return FilterConstants.PRE_TYPE;
  }

  @Override
  public int filterOrder() {
    return 0;
  }

  @Override
  public boolean shouldFilter() {

    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    String shouldFilter = request.getParameter("shouleFilter");
    if (StringUtils.isNotBlank(shouldFilter) && StringUtils.equals("true", shouldFilter)) {
      return true;
    }
    return false;
  }

  @Override
  public Object run() throws ZuulException {

    logger.info("********go into myfilter for zuul *******");

    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    String token = request.getParameter("token");
    if (StringUtils.isBlank(token)) {

      logger.info("token is null");

      requestContext.setSendZuulResponse(false);
      requestContext.setResponseStatusCode(401);

      try {
        requestContext.getResponse().getWriter().write("token is null");
      } catch (IOException e) {
        logger.error("zuul error", e);
      }
      return null;
    }

    return null;
  }
}
